package com.ywjt.platformbusiness.order.fragment;

import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.ywjt.platformbusiness.R;
import com.ywjt.platformbusiness.base.BaseModel;
import com.ywjt.platformbusiness.base.BaseVPFragment;
import com.ywjt.platformbusiness.constants.UrlConstants;
import com.ywjt.platformbusiness.http.HttpRequest;
import com.ywjt.platformbusiness.http.HttpStringCallBack;
import com.ywjt.platformbusiness.order.activity.ActivityOrderFinish;
import com.ywjt.platformbusiness.order.activity.ActivityOrderPostSale;
import com.ywjt.platformbusiness.order.activity.ActivityOrderUnConfirm;
import com.ywjt.platformbusiness.order.activity.ActivityOrderUnPay;
import com.ywjt.platformbusiness.order.activity.ActivityOrderUnSend;
import com.ywjt.platformbusiness.order.adapter.OrderListAdapter;
import com.ywjt.platformbusiness.order.model.OrderListModel;
import com.ywjt.platformbusiness.util.ToastUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class OrderFragment extends BaseVPFragment {
    private OrderListAdapter adapter;
    private RecyclerView rcView;
    private View view;
    private Context context;
    private List<OrderListModel.DataDTO> data;
    private LinearLayout llNodata;

    private int currentPage=1;
    private SmartRefreshLayout refresh;
    private int count=0;
    private int status=0;
    private int posi=0;

    public static OrderFragment newInstance(int status ) {
        Bundle arguments = new Bundle();
        arguments.putInt("status",status);
       OrderFragment fl = new OrderFragment();
        fl.setArguments(arguments);
        return fl;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (view == null) {
            view = inflater.inflate(R.layout.fragment_order, container, false);
            context = getActivity();
            initView();
        }
        return view;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView();
    }

//    @Subscribe(threadMode = ThreadMode.MAIN)
//    public void wxPaySuccess(EventBusBean eventBus){
//        switch (eventBus.getCode()){
//            case 79://
//                Log.e("ttttt","列表");
//                cancelOrder(posi,eventBus.getMsg());
//                break;
//        }
//    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if(hidden){
            if(!EventBus.getDefault().isRegistered(this)){//加上判断
                EventBus.getDefault().unregister(this);
            }
        }
    }

    @Override
    protected void onFragmentVisibleChange(boolean isVisible) {
        if(!isVisible){
            //不可见
            if(!EventBus.getDefault().isRegistered(this)){//加上判断
                EventBus.getDefault().unregister(this);
            }
        }
    }

    @Override
    protected void onFragmentFirstVisible() {

       // getData();
    }

//    //获取数据
//    public void getData(){
//        Map<String, String> map = new HashMap<>();
//        map.put("userId",getUserId(context));
//        map.put("pageNum", String.valueOf(currentPage));
//        map.put("pageSize",String.valueOf(PAGESIZE));
//        map.put("status",String.valueOf(status));
//        new HttpRequest(context).doPost(UrlConstants.goodsOrder_orderList, null, map, OrderListModel.class, new HttpStringCallBack() {
//            @RequiresApi(api = Build.VERSION_CODES.M)
//            @Override
//            public void onSuccess(Object result) {
//                if (result instanceof OrderListModel) {
//                    OrderListModel model=(OrderListModel) result;
//                    if (currentPage == 1) {
//                        data.clear();
//                        count = model.getCount();
//                        if (model.getData().size() > 0) {
//                            data=model.getData();
//                            llNodata.setVisibility(View.GONE);
//                            rcView.setVisibility(View.VISIBLE);
//                            adapter=new OrderList_Adapter(data,status);
//                            rcView.setLayoutManager(new LinearLayoutManager(context));
//                            rcView.setAdapter(adapter);
//                            if (adapter.getItemCount() < count) {
//                                //还有多的数据
//                                refresh.finishRefresh();
//                            } else {
//                                //没有更多数据（上拉加载功能将显示没有更多数据）
//                                refresh.finishRefreshWithNoMoreData();
//                            }
//                            adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
//                                @Override
//                                public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
//                                    if(data.get(position).getGoodsType()==1){
//
//                                        switch (status){
//                                            case -1:
//                                                switch (data.get(position).getStatus()){
//                                                    case 3:
//                                                        //已经取消
//                                                        ActivityOrderCanceled.actionStart(context,data.get(position).getOrderNum());
//                                                        break;
//                                                    case 0:
//                                                        ActivityOrderUnPay.actionStart(context,data.get(position).getOrderNum());
//                                                        break;
//                                                    case 1:
//                                                        ActivityOrderUnSend.actionStart(context,data.get(position).getOrderNum());
//                                                        break;
//                                                    case 2:
//                                                        ActivityOrderUnConfirm.actionStart(context,data.get(position).getOrderNum());
//                                                        break;
//                                                    case 4:
//                                                        ActivityOrderFinish.actionStart(context,data.get(position).getOrderNum());
//                                                        break;
//                                                    default:
//                                                        break;
//                                                }
//                                                break;
//                                            case 3:
//                                                //已经取消
//                                                ActivityOrderCanceled.actionStart(context,data.get(position).getOrderNum());
//                                                break;
//                                            case 0:
//                                                ActivityOrderUnPay.actionStart(context,data.get(position).getOrderNum());
//                                                break;
//                                            case 1:
//                                                ActivityOrderUnSend.actionStart(context,data.get(position).getOrderNum());
//                                                break;
//                                            case 2:
//                                                ActivityOrderUnConfirm.actionStart(context,data.get(position).getOrderNum());
//                                                break;
//                                            case 4:
//                                                ActivityOrderFinish.actionStart(context,data.get(position).getOrderNum());
//                                                break;
//                                            case 5:
//                                                ActivityReturnDetail.actionStart(context,data.get(position).getOrderNum(),data.get(position).getGoodsRefund().getId()+"");
//                                                break;
//                                        }
//
//                                    }else if(data.get(position).getGoodsType()==2){
//                                        Activity_Integral_Order_Detail.actionStart(context,data.get(position).getOrderNum());
//                                    }
//                                }
//                            });
//                            adapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
//                                @Override
//                                public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
//                                    posi=position;
//                                    switch (view.getId()){
//                                        case R.id.tvTipSendGoods:
//                                            //提醒发货
//                                            ToastUtil toastUtil=new ToastUtil(context, R.layout.popu_success,"提醒卖家发货发送消息成功",1);
//                                            toastUtil.show();
//                                            break;
//                                        case R.id.tvCancle:
//                                            //取消订单
//                                            ReasonPickBottomDialog dialog1=new ReasonPickBottomDialog(context,1,"取消订单",2);
//                                            dialog1.show(getFragmentManager());
//                                            break;
//                                        case R.id.tvGotoPay:
//                                            //去支付
//                                            Activity_Pay_Order.actionStart(context,String.valueOf(data.get(posi).getOrderNum()),data.get(posi).getRealPrice().doubleValue(),"");
//                                            break;
//                                            case R.id.tvConfirm:
//                                            //确认收货
//                                            confirmReceipt(position);
//                                            break;
//                                        case R.id.tvCheckTrace:
//                                            //查看物流
//                                            ActivityGoodsTrack.actionStart(context,model.getData().get(position).getExpressCode(),
//                                                    model.getData().get(position).getExpressNum(),
//                                                    model.getData().get(position).getOrderDetailList().get(0).getGoodsCover(),
//                                                    model.getData().get(position).getOrderDetailList().size());
//                                            break;
//                                        case R.id.tvDetail:
//                                            //删除退换货记录
//                                            deleteReturnOrder(position);
//                                            break;
//                                        case R.id.tvDelete:
//                                            //删除订单
//                                            deleteOrder(position);
//                                            break;
//                                    }
//                                }
//                            });
//                        } else {
//                            refresh.finishRefreshWithNoMoreData();
//                            llNodata.setVisibility(View.VISIBLE);
//                            rcView.setVisibility(View.GONE);
//                        }
//                    } else {
//                        data.addAll(model.getData());
//                        adapter.notifyDataSetChanged();
//                        if (adapter.getItemCount() < count) {
//                            //还有多的数据
//                            refresh.finishRefresh();
//                        } else {
//                            //没有更多数据（上拉加载功能将显示没有更多数据）
//                            refresh.finishRefreshWithNoMoreData();
//                        }
//                    }
//                }
//            }
//
//            @Override
//            public void onFailure(int code, String msg) {
//                refresh.finishLoadMore();
//                refresh.finishRefresh();
//            }
//        });
//    }
//
//
    public void initView(){
//        if(!EventBus.getDefault().isRegistered(this)){//加上判断
//            EventBus.getDefault().register(this);
//        }
        status=getArguments().getInt("status",0);
        refresh=view.findViewById(R.id.refresh);
        rcView=view.findViewById(R.id.rcView);
        llNodata=view.findViewById(R.id.llNodata);

        rcView.setVisibility(View.VISIBLE);
        llNodata.setVisibility(View.GONE);
        data=new ArrayList<>();
        data.add(new OrderListModel.DataDTO());
        data.add(new OrderListModel.DataDTO());
        data.add(new OrderListModel.DataDTO());
        data.add(new OrderListModel.DataDTO());



        adapter=new OrderListAdapter(data,status);
        rcView.setLayoutManager(new LinearLayoutManager(context));
        rcView.setAdapter(adapter);
        adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                switch (status){
                    case -1:
                        break;
                    case 0:
                        ActivityOrderUnPay.actionStart(context,"");
                        break;
                    case 1:
                        ActivityOrderUnSend.actionStart(context,"");
                        break;
                    case 2:
                        ActivityOrderUnConfirm.actionStart(context,"");
                        break;
                    case 3:
                        ActivityOrderFinish.actionStart(context,"");
                        break;
                    case 4:
                        //售后
                        ActivityOrderPostSale.actionStart(context,"");
                        break;
                }
            }
        });


       // setView();
    }
//
//    //确认收货
//    public void confirmReceipt(int posi){
//        Map<String, String> map = new HashMap<>();
//        map.put("orderNum", String.valueOf(data.get(posi).getOrderNum()));
//        map.put("userId",getUserId(context));
//        new HttpRequest(context).doPost(UrlConstants.goodsOrder_confirmOrder, "", map, BaseModel.class, new HttpStringCallBack() {
//            @RequiresApi(api = Build.VERSION_CODES.M)
//            @Override
//            public void onSuccess(Object result) {
//                if (result instanceof BaseModel) {
//                    BaseModel bean=(BaseModel)result;
//                    if(bean.getCode()==200){
//                        ToastUtil toastUtil=new ToastUtil(context, R.layout.popu_success1,"收获成功",1);
//                        toastUtil.show();
//                        refresh.autoRefresh();
//                    }
//                }
//            }
//
//            @Override
//            public void onFailure(int code, String msg) {
//                Toast.makeText(context,msg,Toast.LENGTH_SHORT).show();
//            }
//        });
//    }
//
//    //删除订单
//    public void deleteOrder(int posi){
//        Map<String, String> map = new HashMap<>();
//        map.put("orderNum", String.valueOf(data.get(posi).getOrderNum()));
//        map.put("userId",getUserId(context));
//        new HttpRequest(context).doPost(UrlConstants.goodsOrder_removeOrder, "", map, BaseModel.class, new HttpStringCallBack() {
//            @RequiresApi(api = Build.VERSION_CODES.M)
//            @Override
//            public void onSuccess(Object result) {
//                if (result instanceof BaseModel) {
//                    BaseModel bean=(BaseModel)result;
//                    if(bean.getCode()==200){
//                        ToastUtil toastUtil=new ToastUtil(context, R.layout.popu_resetsuccess,"删除订单成功",1);
//                        toastUtil.show();
//                        data.remove(posi);
//                        adapter.notifyDataSetChanged();
//                    }
//                }
//            }
//
//            @Override
//            public void onFailure(int code, String msg) {
//                Toast.makeText(context,msg,Toast.LENGTH_SHORT).show();
//            }
//        });
//    }
//
//    //删除退款订单
//    public void deleteReturnOrder(int posi){
//        Map<String, String> map = new HashMap<>();
//        map.put("id", String.valueOf(data.get(posi).getGoodsRefund().getId()));
//        map.put("userId",getUserId(context));
//        new HttpRequest(context).doPost(UrlConstants.goodsRefund_remove, "", map, BaseModel.class, new HttpStringCallBack() {
//            @RequiresApi(api = Build.VERSION_CODES.M)
//            @Override
//            public void onSuccess(Object result) {
//                if (result instanceof BaseModel) {
//                    BaseModel bean=(BaseModel)result;
//                    if(bean.getCode()==200){
//                        data.remove(posi);
//                        adapter.notifyDataSetChanged();
//                    }
//                }
//            }
//
//            @Override
//            public void onFailure(int code, String msg) {
//                Toast.makeText(context,msg,Toast.LENGTH_SHORT).show();
//            }
//        });
//    }
//
//    //取消订单
//    public void cancelOrder(int posi,String reason){
//        Map<String, String> map = new HashMap<>();
//        map.put("orderNum",data.get(posi).getOrderNum());
//        map.put("userId",getUserId(context));
//        map.put("remark",reason);
//        new HttpRequest(context).doPost(UrlConstants.goodsOrder_cancelOrder, "", map, BaseModel.class, new HttpStringCallBack() {
//            @RequiresApi(api = Build.VERSION_CODES.M)
//            @Override
//            public void onSuccess(Object result) {
//                if (result instanceof BaseModel) {
//                    BaseModel bean=(BaseModel)result;
//                    if(bean.getCode()==200){
//                        ToastUtil toastUtil=new ToastUtil(context, R.layout.popu_success,"取消订单成功",1);
//                        toastUtil.show();
//                        data.get(posi).setStatus(3);
//                        adapter.notifyDataSetChanged();
//                    }else {
//                        Log.e("ttttt",bean.getMessage());
//                    }
//                }
//            }
//
//            @Override
//            public void onFailure(int code, String msg) {
//                Toast.makeText(context,msg,Toast.LENGTH_SHORT).show();
//            }
//        });
//    }
//
//
//    public void setView(){
//        data=new ArrayList<>();
//        refresh.setEnableAutoLoadMore(true);//开启自动加载功能（非必须）
//        refresh.setOnRefreshListener(new OnRefreshListener() {
//            @Override
//            public void onRefresh(final RefreshLayout refreshLayout) {
//                refreshLayout.getLayout().postDelayed(new Runnable() {
//                    @Override
//                    public void run() {
//                        currentPage = 1;
//                        getData();
//                    }
//                }, 1000);
//            }
//        });
//        refresh.setOnLoadMoreListener(new OnLoadMoreListener() {
//            @Override
//            public void onLoadMore(@NonNull final RefreshLayout refreshLayout) {
//                refreshLayout.getLayout().postDelayed(new Runnable() {
//                    @Override
//                    public void run() {
//                        currentPage++;
//                        getData();
//                    }
//                }, 1000);
//            }
//        });
//    }
}
